/* GStreamer
 * Copyright (C) 1999,2000 Erik Walthinsen <omega@cse.ogi.edu>
 *                    2001 Thomas <thomas@apestaart.org>
 *               2005,2006 Wim Taymans <wim@fluendo.com>
 *
 * mixer.c: AsyncMixer element, N in, one out, samples are added
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Library General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Library General Public License for more details.
 *
 * You should have received a copy of the GNU Library General Public
 * License along with this library; if not, write to the
 * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
 * Boston, MA 02111-1307, USA.
 */
/**
 * SECTION:element-mixer
 *
 * <refsect2>
 * The AsyncMixer allows to mix several streams into one by adding the data.
 * Mixed data is clamped to the min/max values of the data format.
 * <title>Example launch line</title>
 * <para>
 * <programlisting>
 * gst-launch audiotestsrc freq=100 ! mixer name=mix ! audioconvert ! alsasink audiotestsrc freq=500 ! mix.
 * </programlisting>
 * This pipeline produces two sine waves mixed together.
 * </para>
 * <para>
 * The AsyncMixer currently mixes all data received on the sinkpads as soon as possible
 * without trying to synchronize the streams.
 * </para>
 * </refsect2>
 *
 * Last reviewed on 2006-05-09 (0.10.7)
 */
/* Element-Checklist-Version: 5 */

#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "gstasyncmixer.h"
#include <gst/audio/audio.h>
#include <string.h>             /* strcmp */

/* highest positive/lowest negative x-bit value we can use for clamping */
#define MAX_INT_32  ((gint32) (0x7fffffff))
#define MAX_INT_16  ((gint16) (0x7fff))
#define MAX_INT_8   ((gint8)  (0x7f))
#define MAX_UINT_32 ((guint32)(0xffffffff))
#define MAX_UINT_16 ((guint16)(0xffff))
#define MAX_UINT_8  ((guint8) (0xff))

#define MIN_INT_32  ((gint32) (0x80000000))
#define MIN_INT_16  ((gint16) (0x8000))
#define MIN_INT_8   ((gint8)  (0x80))
#define MIN_UINT_32 ((guint32)(0x00000000))
#define MIN_UINT_16 ((guint16)(0x0000))
#define MIN_UINT_8  ((guint8) (0x00))

#define GST_CAT_DEFAULT gst_async_mixer_debug
GST_DEBUG_CATEGORY_STATIC (GST_CAT_DEFAULT);

/* elementfactory information */
static const GstElementDetails mixer_details = GST_ELEMENT_DETAILS ("asyncmixer",
    "Generic/Audio",
    "Add N audio channels together",
    "Nigel Sim <nigel.sim@gmail.com>");

static GstStaticPadTemplate gst_async_mixer_src_template =
    GST_STATIC_PAD_TEMPLATE ("src",
    GST_PAD_SRC,
    GST_PAD_ALWAYS,
    GST_STATIC_CAPS (GST_AUDIO_INT_PAD_TEMPLATE_CAPS "; "
        GST_AUDIO_FLOAT_PAD_TEMPLATE_CAPS)
    );

static GstStaticPadTemplate gst_async_mixer_sink_template =
    GST_STATIC_PAD_TEMPLATE ("sink%d",
    GST_PAD_SINK,
    GST_PAD_REQUEST,
    GST_STATIC_CAPS (GST_AUDIO_INT_PAD_TEMPLATE_CAPS "; "
        GST_AUDIO_FLOAT_PAD_TEMPLATE_CAPS)
    );

static void gst_async_mixer_class_init (GstAsyncMixerClass * klass);
static void gst_async_mixer_init (GstAsyncMixer * mixer);
static void gst_async_mixer_finalize (GObject * object);

static gboolean gst_async_mixer_setcaps (GstPad * pad, GstCaps * caps);
static gboolean gst_async_mixer_query (GstPad * pad, GstQuery * query);
static gboolean gst_async_mixer_src_event (GstPad * pad, GstEvent * event);
static gboolean gst_async_mixer_sink_event (GstPad * pad, GstEvent * event);

static GstFlowReturn gst_async_mixer_chain (GstPad * pad, GstBuffer * buffer);

static GstPad *gst_async_mixer_request_new_pad (GstElement * element,
    GstPadTemplate * temp, const gchar * unused);
static void gst_async_mixer_release_pad (GstElement * element, GstPad * pad);

static GstCaps * gst_async_mixer_getcaps (GstPad * pad);

static GstStateChangeReturn gst_async_mixer_change_state (GstElement * element,
    GstStateChange transition);

static void gst_async_mixer_loop (GstAsyncMixer * mixer);

static GstElementClass *parent_class = NULL;


static void
gst_async_mixer_class_init (GstAsyncMixerClass * klass)
{
  GObjectClass *gobject_class;
  GstElementClass *gstelement_class;

  gobject_class = (GObjectClass *) klass;

  gobject_class->finalize = gst_async_mixer_finalize;

  gstelement_class = (GstElementClass *) klass;

  gst_element_class_add_pad_template (gstelement_class,
      gst_static_pad_template_get (&gst_async_mixer_src_template));
  gst_element_class_add_pad_template (gstelement_class,
      gst_static_pad_template_get (&gst_async_mixer_sink_template));
  gst_element_class_set_details (gstelement_class, &mixer_details);

  parent_class = g_type_class_peek_parent (klass);

  gstelement_class->request_new_pad = gst_async_mixer_request_new_pad;
  gstelement_class->release_pad = gst_async_mixer_release_pad;
  gstelement_class->change_state = gst_async_mixer_change_state;
}

static void
gst_async_mixer_init (GstAsyncMixer * mixer)
{
  GstPadTemplate *template;

  template = gst_static_pad_template_get (&gst_async_mixer_src_template);
  mixer->srcpad = gst_pad_new_from_template (template, "src");
  gst_object_unref (template);
  gst_pad_set_getcaps_function (mixer->srcpad,
      GST_DEBUG_FUNCPTR (gst_async_mixer_getcaps));
      //GST_DEBUG_FUNCPTR (gst_pad_proxy_getcaps));
  gst_pad_set_setcaps_function (mixer->srcpad,
      GST_DEBUG_FUNCPTR (gst_async_mixer_setcaps));
  gst_pad_set_query_function (mixer->srcpad,
      GST_DEBUG_FUNCPTR (gst_async_mixer_query));
  gst_pad_set_event_function (mixer->srcpad,
      GST_DEBUG_FUNCPTR (gst_async_mixer_src_event));
  gst_element_add_pad (GST_ELEMENT (mixer), mixer->srcpad);

  mixer->format = GST_ASYNC_MIXER_FORMAT_UNSET;
  mixer->padcount = 0;
  mixer->func = NULL;
  mixer->pads = NULL;
  mixer->caps = NULL;
  mixer->started = FALSE;
  mixer->lock = g_mutex_new();
}

static void
gst_async_mixer_finalize (GObject * object)
{
  GstAsyncMixer *mixer = GST_ASYNC_MIXER (object);
  GSList *item = mixer->pads;
  for (; item ; item = g_slist_next (item)) {
    GstAsyncMixerQueue *queue = (GstAsyncMixerQueue*)item->data;
    g_mutex_free(queue->qlock);
    gst_object_unref(queue->pad);
    queue->pad = NULL;
    // TODO free buffers
  }
  g_slist_free(mixer->pads);
  mixer->pads = NULL;
  g_mutex_free(mixer->lock);

  G_OBJECT_CLASS (parent_class)->finalize (object);
}

GType
gst_async_mixer_get_type (void)
{
  static GType mixer_type = 0;

  if (G_UNLIKELY (mixer_type == 0)) {
    static const GTypeInfo mixer_info = {
      sizeof (GstAsyncMixerClass), NULL, NULL,
      (GClassInitFunc) gst_async_mixer_class_init, NULL, NULL,
      sizeof (GstAsyncMixer), 0,
      (GInstanceInitFunc) gst_async_mixer_init,
    };

    mixer_type = g_type_register_static (GST_TYPE_ELEMENT, "GstAsyncMixer",
        &mixer_info, 0);
    GST_DEBUG_CATEGORY_INIT (GST_CAT_DEFAULT, "asyncmixer", 0,
        "audio channel mixing element");
  }
  return mixer_type;
}

/* clipping versions */
#define MAKE_FUNC(name,type,ttype,min,max)                      \
static void name (type *out, type *in, gint bytes) {            \
  gint i;                                                       \
  for (i = 0; i < bytes / sizeof (type); i++)                   \
    out[i] = CLAMP ((ttype)out[i] + (ttype)in[i], min, max);    \
}

/* non-clipping versions (for float) */
#define MAKE_FUNC_NC(name,type,ttype)                           \
static void name (type *out, type *in, gint bytes) {            \
  gint i;                                                       \
  for (i = 0; i < bytes / sizeof (type); i++)                   \
    out[i] = (ttype)out[i] + (ttype)in[i];                      \
}

/* *INDENT-OFF* */
MAKE_FUNC (add_int32, gint32, gint64, MIN_INT_32, MAX_INT_32)
MAKE_FUNC (add_int16, gint16, gint32, MIN_INT_16, MAX_INT_16)
MAKE_FUNC (add_int8, gint8, gint16, MIN_INT_8, MAX_INT_8)
MAKE_FUNC (add_uint32, guint32, guint64, MIN_UINT_32, MAX_UINT_32)
MAKE_FUNC (add_uint16, guint16, guint32, MIN_UINT_16, MAX_UINT_16)
MAKE_FUNC (add_uint8, guint8, guint16, MIN_UINT_8, MAX_UINT_8)
MAKE_FUNC_NC (add_float64, gdouble, gdouble)
MAKE_FUNC_NC (add_float32, gfloat, gfloat)
/* *INDENT-ON* */

static gboolean
gst_async_mixer_setcaps (GstPad * pad, GstCaps * caps)
{
  GstAsyncMixer *mixer;
  GList *pads;
  GstStructure *structure;
  const char *media_type;
  mixer = GST_ASYNC_MIXER (GST_PAD_PARENT (pad));
  GST_LOG_OBJECT (mixer, "setting caps on pad %p,%s to %" GST_PTR_FORMAT, pad,
      GST_PAD_NAME (pad), caps);
  gst_object_unref(pad);

  g_mutex_lock(mixer->lock);
  if (mixer->caps != NULL){
    if (! gst_caps_is_equal(mixer->caps, caps))
      g_error("New caps don't equal old caps\n");
    g_mutex_unlock(mixer->lock);
    return TRUE;
  }
  g_mutex_unlock(mixer->lock);

  /* FIXME, see if the other pads can accept the format. Also lock the
   * format on the other pads to this new format. */
  g_mutex_lock(mixer->lock);
  pads = GST_ELEMENT (mixer)->pads;
  if (mixer->caps == NULL)
    mixer->caps = gst_caps_copy(caps);
  g_mutex_unlock(mixer->lock);

  /* parse caps now */
  structure = gst_caps_get_structure (caps, 0);
  media_type = gst_structure_get_name (structure);
  if (strcmp (media_type, "audio/x-raw-int") == 0) {
    GST_DEBUG_OBJECT (mixer, "parse_caps sets mixer to format int");
    mixer->format = GST_ASYNC_MIXER_FORMAT_INT;
    gst_structure_get_int (structure, "width", &mixer->width);
    gst_structure_get_int (structure, "depth", &mixer->depth);
    gst_structure_get_int (structure, "endianness", &mixer->endianness);
    gst_structure_get_boolean (structure, "signed", &mixer->is_signed);

    if (mixer->endianness != G_BYTE_ORDER)
      goto not_supported;

    switch (mixer->width) {
      case 8:
        mixer->func = (mixer->is_signed ?
            (GstAsyncMixerFunction) add_int8 : (GstAsyncMixerFunction) add_uint8);
        break;
      case 16:
        mixer->func = (mixer->is_signed ?
            (GstAsyncMixerFunction) add_int16 : (GstAsyncMixerFunction) add_uint16);
        break;
      case 32:
        mixer->func = (mixer->is_signed ?
            (GstAsyncMixerFunction) add_int32 : (GstAsyncMixerFunction) add_uint32);
        break;
      default:
        goto not_supported;
    }
  } else if (strcmp (media_type, "audio/x-raw-float") == 0) {
    GST_DEBUG_OBJECT (mixer, "parse_caps sets mixer to format float");
    mixer->format = GST_ASYNC_MIXER_FORMAT_FLOAT;
    gst_structure_get_int (structure, "width", &mixer->width);

    switch (mixer->width) {
      case 32:
        mixer->func = (GstAsyncMixerFunction) add_float32;
        break;
      case 64:
        mixer->func = (GstAsyncMixerFunction) add_float64;
        break;
      default:
        goto not_supported;
    }
  } else {
    goto not_supported;
  }

  gst_structure_get_int (structure, "channels", &mixer->channels);
  gst_structure_get_int (structure, "rate", &mixer->rate);
  /* precalc bps */
  mixer->bps = (mixer->width / 8) * mixer->channels;
  GST_DEBUG("%s: rate=%d, channels=%d\n", __func__, mixer->rate, mixer->channels);
  return TRUE;

  /* ERRORS */
not_supported:
  {
    GST_DEBUG_OBJECT (mixer, "unsupported format set as caps");
    return FALSE;
  }
}

static GstCaps *
gst_async_mixer_getcaps (GstPad * pad)
{
  GstCaps * caps;
  GstAsyncMixer * mixer = GST_ASYNC_MIXER (GST_PAD_PARENT (pad));

  g_mutex_lock(mixer->lock);
  if (mixer->caps == NULL)
    caps = gst_static_pad_template_get_caps(&gst_async_mixer_sink_template);
  else
    caps = gst_caps_copy(mixer->caps);
  GST_DEBUG("For %s returned %s\n", (pad==mixer->srcpad?"src":"sink"), gst_caps_to_string(caps));
  g_mutex_unlock(mixer->lock);

  return caps;
}
/* FIXME, the duration query should reflect how long you will produce
 * data, that is the amount of stream time until you will emit EOS.
 *
 * For synchronized mixing this is always the max of all the durations
 * of upstream since we emit EOS when all of them finished.
 *
 * We don't do synchronized mixing so this really depends on where the
 * streams where punched in and what their relative offsets are against
 * eachother which we can get from the first timestamps we see.
 *
 * When we add a new stream (or remove a stream) the duration might
 * also become invalid again and we need to post a new DURATION
 * message to notify this fact to the parent.
 * For now we take the max of all the upstream elements so the simple
 * cases work at least somewhat.
 */
static gboolean
gst_async_mixer_query_duration (GstAsyncMixer * mixer, GstQuery * query)
{
  gint64 max;
  gboolean res;
  GstFormat format;
  GstIterator *it;
  gboolean done;

  /* parse format */
  gst_query_parse_duration (query, &format, NULL);

  max = -1;
  res = TRUE;
  done = FALSE;

  it = gst_element_iterate_sink_pads (GST_ELEMENT_CAST (mixer));
  while (!done) {
    GstIteratorResult ires;
    gpointer item;

    ires = gst_iterator_next (it, &item);
    switch (ires) {
      case GST_ITERATOR_DONE:
        done = TRUE;
        break;
      case GST_ITERATOR_OK:
      {
        GstPad *pad = GST_PAD_CAST (item);
        gint64 duration;

        /* ask sink peer for duration */
        res &= gst_pad_query_peer_duration (pad, &format, &duration);
        /* take max from all valid return values */
        if (res) {
          /* valid unknown length, stop searching */
          if (duration == -1) {
            max = duration;
            done = TRUE;
          }
          /* else see if bigger than current max */
          else if (duration > max)
            max = duration;
        }
        break;
      }
      case GST_ITERATOR_RESYNC:
        max = -1;
        res = TRUE;
        break;
      default:
        res = FALSE;
        done = TRUE;
        break;
    }
  }
  gst_iterator_free (it);

  if (res) {
    /* and store the max */
    gst_query_set_duration (query, format, max);
  }

  return res;
}

static gboolean
gst_async_mixer_query (GstPad * pad, GstQuery * query)
{
  GstAsyncMixer *mixer = GST_ASYNC_MIXER (gst_pad_get_parent (pad));
  gboolean res = FALSE;

  switch (GST_QUERY_TYPE (query)) {
    case GST_QUERY_POSITION:
    {
      GstFormat format;

      gst_query_parse_position (query, &format, NULL);

      switch (format) {
        case GST_FORMAT_TIME:
          /* FIXME, bring to stream time, might be tricky */
          gst_query_set_position (query, format, mixer->timestamp);
          res = TRUE;
          break;
        case GST_FORMAT_DEFAULT:
          gst_query_set_position (query, format, mixer->offset);
          res = TRUE;
          break;
        default:
          break;
      }
      break;
    }
    case GST_QUERY_DURATION:
      res = gst_async_mixer_query_duration (mixer, query);
      break;
    default:
      /* FIXME, needs a custom query handler because we have multiple
       * sinkpads */
      res = gst_pad_query_default (pad, query);
      break;
  }

  gst_object_unref (mixer);
  return res;
}

static gboolean
forward_event_func (GstPad * pad, GValue * ret, GstEvent * event)
{
  gst_event_ref (event);
  GST_LOG_OBJECT (pad, "About to send event %s", GST_EVENT_TYPE_NAME (event));
  if (!gst_pad_push_event (pad, event)) {
    g_value_set_boolean (ret, FALSE);
    GST_WARNING_OBJECT (pad, "Sending event  %p (%s) failed.",
        event, GST_EVENT_TYPE_NAME (event));
  } else {
    GST_LOG_OBJECT (pad, "Sent event  %p (%s).",
        event, GST_EVENT_TYPE_NAME (event));
  }
  gst_object_unref (pad);
  return TRUE;
}

/* forwards the event to all sinkpads, takes ownership of the
 * event
 *
 * Returns: TRUE if the event could be forwarded on all
 * sinkpads.
 */
static gboolean
forward_event (GstAsyncMixer * mixer, GstEvent * event)
{
  gboolean ret;
  GstIterator *it;
  GValue vret = { 0 };

  GST_LOG_OBJECT (mixer, "Forwarding event %p (%s)", event,
      GST_EVENT_TYPE_NAME (event));

  ret = TRUE;

  g_value_init (&vret, G_TYPE_BOOLEAN);
  g_value_set_boolean (&vret, TRUE);
  it = gst_element_iterate_sink_pads (GST_ELEMENT_CAST (mixer));
  gst_iterator_fold (it, (GstIteratorFoldFunction) forward_event_func, &vret,
      event);
  gst_iterator_free (it);
  gst_event_unref (event);

  ret = g_value_get_boolean (&vret);

  return ret;
}

static gboolean
gst_async_mixer_src_event (GstPad * pad, GstEvent * event)
{
  GstAsyncMixer *mixer;
  gboolean result;

  mixer = GST_ASYNC_MIXER (gst_pad_get_parent (pad));

  switch (GST_EVENT_TYPE (event)) {
    case GST_EVENT_QOS:
      /* QoS might be tricky */
      result = FALSE;
      break;
    case GST_EVENT_SEEK:
    {
      GstSeekFlags flags;
      GstSeekType curtype;
      gint64 cur;

      /* parse the flushing flag */
      gst_event_parse_seek (event, NULL, NULL, &flags, &curtype, &cur, NULL,
          NULL);

      /* check if we are flushing */
      if (flags & GST_SEEK_FLAG_FLUSH) {
        /* make sure we accept nothing anymore and return WRONG_STATE */
        //gst_collect_pads_set_flushing (mixer->collect, TRUE);

        /* flushing seek, start flush downstream, the flush will be done
         * when all pads received a FLUSH_STOP. */
        gst_pad_push_event (mixer->srcpad, gst_event_new_flush_start ());
      }

      /* now wait for the collected to be finished and mark a new
       * segment */
      //GST_OBJECT_LOCK (mixer->collect);
      if (curtype == GST_SEEK_TYPE_SET)
        mixer->segment_position = cur;
      else
        mixer->segment_position = 0;
      mixer->segment_pending = TRUE;
      //GST_OBJECT_UNLOCK (mixer->collect);

      result = forward_event (mixer, event);
      break;
    }
    case GST_EVENT_NAVIGATION:
      /* navigation is rather pointless. */
      result = FALSE;
      break;
    default:
      /* just forward the rest for now */
      result = forward_event (mixer, event);
      break;
  }
  gst_object_unref (mixer);

  return result;
}

static gboolean
gst_async_mixer_sink_event (GstPad * pad, GstEvent * event)
{
  GstAsyncMixer *mixer;
  gboolean ret = TRUE;

  mixer = GST_ASYNC_MIXER (gst_pad_get_parent (pad));

  GST_DEBUG ("Got %s event on pad %s:%s", GST_EVENT_TYPE_NAME (event),
      GST_DEBUG_PAD_NAME (pad));

  switch (GST_EVENT_TYPE (event)) {
    case GST_EVENT_FLUSH_STOP:
      /* mark a pending new segment. This event is synchronized
       * with the streaming thread so we can safely update the
       * variable without races. It's somewhat weird because we
       * assume the collectpads forwarded the FLUSH_STOP past us
       * and downstream (using our source pad, the bastard!).
       */
      mixer->segment_pending = TRUE;
      break;
    default:
      break;
  }

  /* now GstCollectPads can take care of the rest, e.g. EOS */
  //ret = mixer->collect_event (pad, event);

  gst_object_unref (mixer);
  return ret;
}
static GstPad *
gst_async_mixer_request_new_pad (GstElement * element, GstPadTemplate * templ,
    const gchar * unused)
{
  gchar *name;
  GstAsyncMixer *mixer;
  GstPad *newpad;
  gint padcount;

  if (templ->direction != GST_PAD_SINK)
    goto not_sink;

  mixer = GST_ASYNC_MIXER (element);

  /* increment pad counter */
  padcount = g_atomic_int_exchange_and_add (&mixer->padcount, 1);

  name = g_strdup_printf ("sink%d", padcount);
  newpad = gst_pad_new_from_template (templ, name);
  GST_DEBUG_OBJECT (mixer, "request new pad %s", name);
  g_free (name);

/*  gst_pad_set_getcaps_function (newpad,
      GST_DEBUG_FUNCPTR (gst_pad_proxy_getcaps)); */
  gst_pad_set_getcaps_function (newpad, 
      GST_DEBUG_FUNCPTR (gst_async_mixer_getcaps));
  gst_pad_set_setcaps_function (newpad, 
      GST_DEBUG_FUNCPTR (gst_async_mixer_setcaps));
  //gst_collect_pads_add_pad (mixer->collect, newpad, sizeof (GstCollectData));
  gst_pad_set_chain_function (newpad,
      GST_DEBUG_FUNCPTR (gst_async_mixer_chain));

  /* FIXME: hacked way to override/extend the event function of
   * GstCollectPads; because it sets its own event function giving the
   * element no access to events */
  //mixer->collect_event = (GstPadEventFunction) GST_PAD_EVENTFUNC (newpad);
  gst_pad_set_event_function (newpad, GST_DEBUG_FUNCPTR (gst_async_mixer_sink_event));

  /* takes ownership of the pad */
  if (!gst_element_add_pad (GST_ELEMENT (mixer), newpad))
    goto could_not_add;

  GstAsyncMixerQueue *q = g_malloc(sizeof(GstAsyncMixerQueue));
  q->pad = newpad;
  q->queue = g_queue_new(); 
  q->qlock = g_mutex_new();

  g_mutex_lock(mixer->lock);
  GST_DEBUG("lock mixer\n");
  mixer->pads = g_slist_append(mixer->pads, q);
  GST_DEBUG("unlock mixer\n");
  g_mutex_unlock(mixer->lock);

  if (!mixer->started){
    gst_pad_start_task (mixer->srcpad,
        (GstTaskFunction) gst_async_mixer_loop, mixer);
    mixer->started = TRUE;
  }

 
  return newpad;

  /* errors */
not_sink:
  {
    g_warning ("gstmixer: request new pad that is not a SINK pad\n");
    return NULL;
  }
could_not_add:
  {
    GST_DEBUG_OBJECT (mixer, "could not add pad");
    //gst_collect_pads_remove_pad (mixer->collect, newpad);
    gst_object_unref (newpad);
    return NULL;
  }
}

static void
gst_async_mixer_release_pad (GstElement * element, GstPad * pad)
{
  GstAsyncMixer *mixer;

  mixer = GST_ASYNC_MIXER (element);

  GST_DEBUG_OBJECT (mixer, "release pad %s:%s", GST_DEBUG_PAD_NAME (pad));

  //gst_collect_pads_remove_pad (mixer->collect, pad);
  gst_element_remove_pad (element, pad);
}

static void
gst_async_mixer_loop (GstAsyncMixer * mixer)
{
  /*
   * combine channels by adding sample values
   * basic algorithm :
   * - this function is called when all pads have a buffer
   * - get available bytes on all pads.
   * - repeat for each input pad :
   *   - read available bytes, copy or add to target buffer
   *   - if there's an EOS event, remove the input channel
   * - push out the output buffer
   */
  guint size=0;
  guint count=0;
  GSList *source;
  GstBuffer *outbuf;
  GstFlowReturn ret;
  gpointer outbytes;

  /* this is fatal */
  if (G_UNLIKELY (mixer->func == NULL))
    goto not_negotiated;

  /* get available bytes for reading, this can be 0 which could mean
   * empty buffers or EOS, which we will catch when we loop over the
   * pads. */
  //size = g_slist_length (source);

  /*GST_LOG_OBJECT (mixer,
      "starting to cycle through channels, %d bytes available (bps = %d)", size,
      mixer->bps);*/

  outbuf = NULL;
  outbytes = NULL;
  
  g_mutex_lock(mixer->lock);
  //g_print("%s: lock mixer\n", __func__);
  source = mixer->pads;
  for (; source ; source = g_slist_next (source)) {
    GstAsyncMixerQueue *queue;
    GstBuffer *data;
    guint8 *bytes;
    guint len;

    queue = (GstAsyncMixerQueue *) source->data;

    g_mutex_lock(queue->qlock);
    //g_print("%s: lock queue\n", __func__);
    /* get pointer to copy size bytes */
    len = g_queue_get_length (queue->queue);
    /* length 0 means EOS or an empty buffer so we still need to flush in
     * case of an empty buffer. */
    if (len == 0) {
      GST_LOG_OBJECT (mixer, "channel %p: no bytes available", queue->pad);
      //g_print("%s: unlock queue\n", __func__);
      g_mutex_unlock(queue->qlock);
      continue;
    }
    count++;
    data = (GstBuffer*)g_queue_pop_head (queue->queue);
    size = GST_BUFFER_SIZE(data);
  
    bytes = GST_BUFFER_DATA(data);

    g_mutex_unlock(queue->qlock);
    //g_print("%s: unlock queue\n", __func__);

    if (outbuf == NULL) {
      /*GST_LOG_OBJECT (mixer, "channel %p: making output buffer of %d bytes",
          data, size);*/

      /* first buffer, alloc size bytes. FIXME, we can easily subbuffer
       * and _make_writable. */
      outbuf = gst_buffer_new_and_alloc (size);
      outbytes = GST_BUFFER_DATA (outbuf);
      gst_buffer_set_caps (outbuf, mixer->caps);

      memset (outbytes, 0, size);

      GST_LOG_OBJECT (mixer, "channel %p: copying %d bytes from data %p",
          data, size, bytes);

      /* and copy the data into it */
      memcpy (outbytes, bytes, size);
    } else {
      GST_LOG_OBJECT (mixer, "channel %p: mixing %d bytes from data %p",
          data, size, bytes);
      /* other buffers, need to add them */
      mixer->func ((gpointer) outbytes, (gpointer) bytes, size);
    }
    // We have held this buffer over from another thread. Unref it.
    gst_buffer_unref(data);
  }

  /* can only happen when no pads to collect or all EOS */
  if (outbuf == NULL)
    goto eos;

  /* our timestamping is very simple, just an ever incrementing
   * counter, the new segment time will take care of their respective
   * stream time. */
  if (mixer->segment_pending) {
    GstEvent *event;

    /* FIXME, use rate/applied_rate as set on all sinkpads.
     * We could potentially figure out the duration as well using
     * the current segment positions and the stated stop positions.
     * Also we just start from stream time 0 which is rather
     * weird. For non-synchronized mixing, the time should be
     * the min of the stream times of all received segments,
     * rationale being that the duration is at least going to
     * be as long as the earliest stream we start mixing. This
     * would also be correct for synchronized mixing but then
     * the later streams would be delayed until the stream times
     * match.
     */
    event = gst_event_new_new_segment_full (FALSE, 1.0,
        1.0, GST_FORMAT_TIME, mixer->timestamp, -1, mixer->segment_position);

    gst_pad_push_event (mixer->srcpad, event);
    mixer->segment_pending = FALSE;
    mixer->segment_position = 0;
  }

  /* set timestamps on the output buffer */
  GST_BUFFER_TIMESTAMP (outbuf) = mixer->timestamp;
  GST_BUFFER_OFFSET (outbuf) = mixer->offset;

  /* for the next timestamp, use the sample counter, which will
   * never accumulate rounding errors */
  mixer->offset += size / mixer->bps;
  mixer->timestamp = gst_util_uint64_scale_int (mixer->offset,
      GST_SECOND, mixer->rate);

  /* now we can set the duration of the buffer */
  GST_BUFFER_DURATION (outbuf) = mixer->timestamp -
      GST_BUFFER_TIMESTAMP (outbuf);

  /* send it out */
  //g_print("%s: pad=%s buf=%s\n", __func__, gst_caps_to_string(GST_PAD_CAPS(mixer->srcpad)), gst_caps_to_string(GST_BUFFER_CAPS(outbuf)));
  if (count > 1)
    GST_DEBUG("Mixed %d channels\n", count);
  /*GST_LOG_OBJECT (mixer, "pushing outbuf, timestamp %" GST_TIME_FORMAT,
      GST_TIME_ARGS (GST_BUFFER_TIMESTAMP (outbuf)));*/
  g_mutex_unlock(mixer->lock);
  //g_print("%s: unlock mixer\n",__func__);
  if (count > 0)
    ret = gst_pad_push (mixer->srcpad, outbuf);

  return;

  /* ERRORS */
not_negotiated:
  {
    /*GST_ELEMENT_ERROR (mixer, STREAM, FORMAT, (NULL),
        ("Unknown data received, not negotiated"));*/
    g_mutex_unlock(mixer->lock);
    //g_print("%s: unlock mixer\n", __func__);
    return;
  }
eos:
  {
    //g_print("%s: unlock mixer\n",__func__);
    g_mutex_unlock(mixer->lock);
    GST_DEBUG_OBJECT (mixer, "no data available, must be EOS");
    //gst_pad_push_event (mixer->srcpad, gst_event_new_eos ());
    return ;
  }
}

static GstStateChangeReturn
gst_async_mixer_change_state (GstElement * element, GstStateChange transition)
{
  GstAsyncMixer *mixer;
  GstStateChangeReturn ret;

  mixer = GST_ASYNC_MIXER (element);

  switch (transition) {
    case GST_STATE_CHANGE_NULL_TO_READY:
      break;
    case GST_STATE_CHANGE_READY_TO_PAUSED:
      mixer->timestamp = 0;
      mixer->offset = 0;
      mixer->segment_pending = TRUE;
      mixer->segment_position = 0;
      gst_segment_init (&mixer->segment, GST_FORMAT_UNDEFINED);
      break;
    case GST_STATE_CHANGE_PAUSED_TO_PLAYING:
      //gst_pad_start_task (mixer->srcpad,
      //  (GstTaskFunction) gst_async_mixer_loop, mixer);
      break;
    case GST_STATE_CHANGE_PAUSED_TO_READY:
      /* need to unblock the collectpads before calling the
       * parent change_state so that streaming can finish */
      break;
    default:
      break;
  }

  ret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);

  switch (transition) {
    default:
      break;
  }

  return ret;
}

/*
 * In this fuction we 
 */
static GstFlowReturn gst_async_mixer_chain (GstPad * pad, GstBuffer * buffer){
  GST_DEBUG("%s: Buf pad = %p size = %d caps=%s\n", __func__, pad, GST_BUFFER_SIZE(buffer), gst_caps_to_string(GST_PAD_CAPS(pad)));
  GstAsyncMixer *mixer = GST_ASYNC_MIXER (gst_pad_get_parent (pad));
  g_mutex_lock(mixer->lock);
  GST_DEBUG("%s: lock mixer\n", __func__);
  GSList *item = mixer->pads;
  for (; item ; item = g_slist_next (item)) {
    GstAsyncMixerQueue *data = (GstAsyncMixerQueue *) item->data;
    if (pad == data->pad) {
      g_mutex_lock(data->qlock);
      GST_DEBUG("%s: lock queue\n", __func__);
      g_queue_push_tail (data->queue, buffer);
      GST_DEBUG("Queue size for %p is %d\n", data->pad, g_queue_get_length(data->queue));
      g_mutex_unlock(data->qlock);
      GST_DEBUG("%s: unlock queue\n", __func__);
      g_mutex_unlock(mixer->lock);
      GST_DEBUG("%s: unlock mixer\n", __func__);
      return GST_FLOW_OK;
    }
  }
  g_mutex_unlock(mixer->lock);
  GST_DEBUG("%s: ulock mixer. Couldn't not find pad\n", __func__);
  return GST_FLOW_ERROR;
}

static gboolean
plugin_init (GstPlugin * plugin)
{
  if (!gst_element_register (plugin, "asyncmixer", GST_RANK_NONE, GST_TYPE_ASYNC_MIXER)) {
    return FALSE;
  }

  return TRUE;
}

GST_PLUGIN_DEFINE (GST_VERSION_MAJOR,
    GST_VERSION_MINOR,
    "asyncmixer",
    "Adds multiple streams",
    plugin_init, VERSION, "LGPL", "AsyncMixer", "nigel.sim@gmail.com")

